#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <imago.h>
#include <hashtbl.h>
#include "texture.h"

struct texture {
	int xsz, ysz;
	float *pixels;
};

static void *texdb;

int init_texman(void)
{
	if(!(texdb = htab_create(htab_hash_string, htab_cmp_string))) {
		fprintf(stderr, "find_texture: failed to create texture database: %s\n", strerror(errno));
		return -1;
	}
	return 0;
}

struct texture *get_texture(const char *fname)
{
	int xsz, ysz;
	float *pixels;
	struct texture *tex;

	if((tex = htab_get(texdb, (char*)fname))) {
		return tex;
	}

	set_image_option(IMG_OPT_FLOAT, 1);
	if(!(pixels = load_image(fname, &xsz, &ysz))) {
		return 0;
	}

	if(!(tex = malloc(sizeof *tex))) {
		free_image(pixels);
		return 0;
	}

	tex->xsz = xsz;
	tex->ysz = ysz;
	tex->pixels = pixels;

	if(htab_add(texdb, (char*)fname, tex) == -1) {
		perror("error adding texture to database");
		free(tex);
		return 0;
	}
	return tex;
}

void free_texture(struct texture *tex)
{
	/* TODO: remove from texture database */
	free_image(tex->pixels);
	free(tex);
}

vec4_t tex_lookup(struct texture *tex, vec4_t tc)
{
	int tx = (int)(tc.x * tex->xsz) % tex->xsz;
	int ty = (int)(tc.y * tex->ysz) % tex->ysz;

	float *pix = tex->pixels + ty * tex->xsz * 4 + tx;
	return v4_cons(pix[0], pix[1], pix[2], pix[3]);
}
